﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Common;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.mSA.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mSA.UI
{
    public partial class frm_SA_DN_CBM_WT : frmBaseChild
    {
        DataTable dt_FinishCal = new DataTable();
        DataTable dt_SendMail1 = new DataTable();
        DataTable dt_SendMail2 = new DataTable();
        DataTable dt_SendMail3 = new DataTable();
        string strWhere_BU = "", strWhere_DN = "", strWhere_DT = "";
        string[] strBUList = null;
        public frm_SA_DN_CBM_WT()
        {
            InitializeComponent();
        }
        private void frm_SA_DN_CBM_WT_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            //加载BU
            checkedComboBoxEdit1.Properties.Items.Clear();
            string[] strs = new string[] { "HK", "EX", "PRC" };
            checkedComboBoxEdit1.Properties.Items.AddRange(strs);

            gridControl1.UseEmbeddedNavigator = true;//显示底部数据导航器
            gridControl2.UseEmbeddedNavigator = true;//显示底部数据导航器
            //新增鼠标右键功能
            frmGridViewCust.RegisterGrid(gridView1);
            DevStyle.SetGridControlLayout(gridControl1, false);
            //新增鼠标右键功能
            frmGridViewCust.RegisterGrid(gridView2);
            DevStyle.SetGridControlLayout(gridControl2, false);
        }
        private void sbtnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                strBUList = checkedComboBoxEdit1.EditValue.ToString().Replace(", ", ",").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (strBUList.Length <= 0 && memoExEdit1.Text.Length <= 0 && memoExEdit2.Text.Length <= 0 && dateEdit1.Text.Length <= 0 && dateEdit2.Text.Length <= 0)
                {
                    DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show("没有选择查询条件,数据计算时间过慢,是否继续？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.No)
                    {
                        return;
                    }
                }
                gridControl1.DataSource = new DataTable();
                gridControl2.DataSource = new DataTable();
                Refreshes();
                if (dt_FinishCal.Rows.Count <= 0)
                {
                    XtraMessageBox.Show("查询不到任何数据，请确认输入条件是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                Calculate_CBM();
                if (dt_FinishCal.Select("SL in ('CE','CN','CD') or (ISNULL(UNIT_VOLUME,0)>0  and  ISNULL(UNIT_WEIGHT,0)>0)").Length > 0)
                    gridControl2.DataSource = dt_FinishCal.Select("SL in ('CE','CN','CD') or (ISNULL(UNIT_VOLUME,0)>0  and  ISNULL(UNIT_WEIGHT,0)>0)").CopyToDataTable();
               
                if (dt_FinishCal.Select("SL not in ('CE','CN','CD') and (ISNULL(UNIT_VOLUME, 0) <= 0  or  ISNULL(UNIT_WEIGHT, 0) <= 0)").Length > 0)
                {
                    DataTable dtMerge = new DataTable();
                    dt_SendMail1 = new DataTable();
                    dt_SendMail2 = new DataTable();
                    dt_SendMail3 = new DataTable();
                    //未完成里面SL为CE或CD或CN的默认放到已完成里面   
                    DataTable dataTable = dt_FinishCal.Select("SL not in ('CE','CN','CD') and (ISNULL(UNIT_VOLUME, 0) <= 0  or  ISNULL(UNIT_WEIGHT, 0) <= 0)").CopyToDataTable();
                        
                    gridControl1.DataSource = dataTable;
                    if (dataTable.Select("MATERIAL_NO like '598%' and MRP_CONTROLLER like 'Z%' ").Length > 0)
                        dt_SendMail1 = dataTable.Select("MATERIAL_NO like '598%' and MRP_CONTROLLER like 'Z%'  ").CopyToDataTable();
                    if (dataTable.Select("MRP_CONTROLLER like 'Z%' and (MATERIAL_NO like '596%' or MATERIAL_NO like '696%')").Length > 0)
                        dt_SendMail2 = dataTable.Select("MRP_CONTROLLER like 'Z%' and (MATERIAL_NO like '596%' or MATERIAL_NO like '696%')").CopyToDataTable();

                    dtMerge.Merge(dt_SendMail1);
                    dtMerge.Merge(dt_SendMail2);
                    IEnumerable<DataRow> dataRows = dataTable.AsEnumerable().Except(dtMerge.AsEnumerable(), DataRowComparer.Default);
                    if (dataRows.ToList().Count > 0)
                        dt_SendMail3 = dataRows.CopyToDataTable();
                }
                //导出Excel
                DoExport();


            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        private void Refreshes()
        {

            strWhere_BU = ""; strWhere_DN = ""; strWhere_DT = "";
            StringBuilder sbmemoEx1 = new StringBuilder();
            StringBuilder sbmemoEx2 = new StringBuilder();
            if (strBUList != null && strBUList.Length >= 0)
            {
                if (strBUList.Contains("HK") && strBUList.Contains("EX") && strBUList.Contains("PRC"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'HK%'" +
                        " OR TRANSPORT_NO LIKE 'EX%'" +
                        " OR TRANSPORT_NO LIKE 'TX%'OR TRANSPORT_NO LIKE 'SH%' OR TRANSPORT_NO LIKE 'BJ%' OR TRANSPORT_NO LIKE 'SCDMO%') ";
                }
                else if (strBUList.Contains("HK") && strBUList.Contains("EX"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'HK%'" +
                        " OR TRANSPORT_NO LIKE 'EX%')";
                }
                else if (strBUList.Contains("HK") && strBUList.Contains("PRC"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'HK%'" +
                        " OR TRANSPORT_NO LIKE 'TX%'OR TRANSPORT_NO LIKE 'SH%' OR TRANSPORT_NO LIKE 'BJ%' OR TRANSPORT_NO LIKE 'SCDMO%') ";
                }
                else if (strBUList.Contains("EX") && strBUList.Contains("PRC"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'EX%'" +
                        " OR TRANSPORT_NO LIKE 'TX%'OR TRANSPORT_NO LIKE 'SH%' OR TRANSPORT_NO LIKE 'BJ%' OR TRANSPORT_NO LIKE 'SCDMO%') ";
                }
                else if (strBUList.Contains("HK"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'HK%')";
                }
                else if (strBUList.Contains("EX"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'EX%')";
                }
                else if (strBUList.Contains("PRC"))
                {
                    strWhere_BU = "AND (TRANSPORT_NO LIKE 'TX%'OR TRANSPORT_NO LIKE 'SH%' OR TRANSPORT_NO LIKE 'BJ%' OR TRANSPORT_NO LIKE 'SCDMO%')";
                }

            }
            if (!string.IsNullOrEmpty(dateEdit1.Text))
            {
                if (!string.IsNullOrEmpty(dateEdit2.Text))
                    strWhere_DT = "AND LOADING_DATE>='" + dateEdit1.Text + "' AND LOADING_DATE<='" + dateEdit2.Text + "'";
                else
                    strWhere_DT = "AND  LOADING_DATE='" + dateEdit1.Text + "'";
            }
            if (string.IsNullOrEmpty(dateEdit1.Text) && !string.IsNullOrEmpty(dateEdit2.Text))
            {
                XtraMessageBox.Show("装车日期必须先输入开始时间！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!string.IsNullOrEmpty(memoExEdit1.Text))
            {
                string[] str1 = memoExEdit1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                string[] str2 = memoExEdit2.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                if (str2.Length > 0)
                {
                    if (str1.Length > 1 || str2.Length > 1)
                    {
                        XtraMessageBox.Show("出货通知单范围查询时单个框只能输入一个值！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    //区间范围查询
                    else
                    {
                        strWhere_DN = "AND TRANSPORT_NO between '" + str1[0] + "' and '" + str2[0] + "'";
                    }
                }
                else
                {
                    sbmemoEx1.AppendFormat(" AND TRANSPORT_NO IN('{0}') ", string.Join("','", str1.ToArray()));
                    strWhere_DN = sbmemoEx1.ToString();
                }

            }

            string strSql = @"SELECT a.TRANSPORT_NO ,a.ORDER_NO ,a.LINE_NO ,a.SL ,a.MATERIAL_NO ,
            a.MATERIAL_DESC ,a.MO_NO ,a.PRODUCT_LINE ,a.PRODUCT_ALLOCATION ,a.SHIPPING_QTY ,a.PRODUCT_ROUTING ,
            b.CARTON_QTY ,b.VOLUME_LENGTH,b.VOLUME_WIDTH,b.VOLUME_HEIGHT,
            b.UNIT_VOLUME ,SHIPPING_VOLUME,
            b.UNIT_WEIGHT ,SHIPPING_WEIGHT,
            b.SAVE_USER ,b.SAVE_TIME ,a.TEST_REMARK ,b.CAL_TYPE,a.ORDER_QTY,
            a.DELIVERY_DATE,a.LOADING_DATE,a.CUSTOMER_NAME,a.STOCK_QTY,a.MRP_CONTROLLER,a.UP_LINE,a.MODEL_NO,a.DISTINATION
            FROM
            (SELECT *
            FROM Transfer_SA_DN_List WHERE 1=1 "
             + strWhere_BU + strWhere_DN + strWhere_DT + @") AS a
            LEFT JOIN SA_CBM_WT_Calculated AS b
            ON a.TRANSPORT_NO=b.TRANSPORT_NO AND a.ORDER_NO=b.ORDER_NO AND a.LINE_NO=b.LINE_NO";

            dt_FinishCal = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);

        }
        //计算CBM和重量
        private void Calculate_CBM()
        {
            try
            {
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                //按用户筛选条件重新匹配DataTable
                if (gridView1.ActiveFilterCriteria != null)
                {
                    var filteredDataView = new DataView(gridControl1.DataSource as DataTable);
                    filteredDataView.RowFilter =
                        DevExpress.Data.Filtering.CriteriaToWhereClauseHelper.GetDataSetWhere(gridView1.ActiveFilterCriteria);
                    dt_FinishCal = filteredDataView.ToTable();
                }
                if (dt_FinishCal != null && dt_FinishCal.Rows.Count > 0)
                {
                    string sapError = "";
                    //获得单位转换表
                    DataTable table_UnitConvert = Common.CRUDHelper.Get_Unit_Convert();
                    #region 包装体基础数据获取并更新
                    //获取DN单去重的物料号
                    DataTable table_mes = Common.DataTableHelper.Distinct(dt_FinishCal, new string[] { "MATERIAL_NO" });
                    //修改物料列名为SAP对接列名
                    table_mes.Columns["MATERIAL_NO"].ColumnName = "MATNR";
                    //获取SAP传回来的数据
                    DataTable table_sap = Common.GetSapData.ReturnSapTable(table_mes, out sapError);
                    if (sapError.Trim().Length > 0)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("无法根据DN表取得SAP数据！\r\n" + sapError, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    //重新修改SAP回传数据表的字段名
                    table_sap = Common.GetDataTable.dataTable_NewColums(table_sap);
                    //获取【SA_CBM_WT_From_SAP】符合条件的数据
                    DataTable table_cbm_wt = Common.GetDataTable.Get_SA_CBM_WT_From_SAP();
                    DataTable dtRetDif = new DataTable();//定义table_sap与table_cbm_wt对比后返回的不同数据(差异部分包含本身table_sap)
                    DataTable dtRetDif2 = new DataTable();//定义需要更新的DataTable
                                                          //获取两表差异数据table_sap、table_cbm_wt 字段顺利必需一致
                    Common.DataTableHelper.CompareDt(table_sap, table_cbm_wt, "MATERIAL_NO", out dtRetDif2, out dtRetDif);
                    //得到差异部分插入更新数据表【SA_CBM_WT_From_SAP】
                    //新增两行到表dtRetDif
                    dtRetDif = Common.GetDataTable.dataTable_AddColums(dtRetDif);
                    if (Common.CRUDHelper.Insert_Batch(dtRetDif, "SA_CBM_WT_From_SAP"))
                    {
                        //成功插入后再更新 
                        Common.CRUDHelper.Update_Table(dtRetDif2);
                    }
                    #endregion

                    #region MO BOM物料基础数据获取并更新
                    //获取【MO_BOM】符合条件的数据--因在100多万数据中查询，速度会慢                        
                    DataTable table_mes_mo_bom = Common.GetDataTable.Get_MO_BOM(dt_FinishCal);
                    //再次通过SAP接口获取返回结果
                    table_mes_mo_bom.Columns["MATERIAL_NO"].ColumnName = "MATNR";
                    //获取SAP传回来的数据
                    DataTable table_sap_mo_bom = Common.GetSapData.ReturnSapTable(table_mes_mo_bom, out sapError);
                    if (sapError.Trim().Length > 0)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("无法根据MO_BOM表取得SAP数据！\r\n" + sapError, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    //重新修改SAP回传数据表的字段名
                    table_sap_mo_bom = Common.GetDataTable.dataTable_NewColums(table_sap_mo_bom);
                    DataTable dtRetDif_Add = new DataTable();//定义需要插入的DataTable
                    DataTable dtRetDif_Update = new DataTable();//定义需要更新的DataTable
                    Common.DataTableHelper.CompareDt(table_sap_mo_bom, table_cbm_wt, "MATERIAL_NO", out dtRetDif_Update, out dtRetDif_Add);
                    dtRetDif_Add = Common.GetDataTable.dataTable_AddColums(dtRetDif_Add);
                    if (Common.CRUDHelper.Insert_Batch(dtRetDif_Add, "SA_CBM_WT_From_SAP"))
                    {
                        //成功插入后再更新 
                        Common.CRUDHelper.Update_Table(dtRetDif_Update);
                    }
                    //回刷最终SAP数据到页面
                    table_sap.Merge(table_sap_mo_bom);

                    #endregion

                    #region 后台临时表创建及取人工修正数据
                    //取人工修正数据
                    //***同时加人工修正标记，即在计算方法(Cal_Type)列写入‘人工修正‘，后面将不再执行其他计算逻辑，等同于SL not in ('CE','CN')
                    DataTable table_manual = Common.GetDataTable.Get_WH_CBM_WT_Revised();
                    DataTable table_Temp = Common.GetDataTable.Get_SA_CBM_WT_Calculated();
                    DataTable table_DN_Temp = table_Temp.Clone();
                    table_DN_Temp = Common.GetDataTable.Insert_DataTable(dt_FinishCal, table_DN_Temp, table_manual);

                    //***测试队段只复制工艺路线之前的字段，后面计算字段不复制，以便可以反复测试
                    //***正式发布时按用户需求确定是仅复制非计算字段（全部重算），还量全部复制（即跳过有重量的项目）
                    //***如果用户要求任何情况下，均全部重算，则可取消后面检查重量为0逻辑-2020/9/3
                    if (table_DN_Temp.Select("SL not in ('CE','CN') ").Length > 0)
                        table_DN_Temp = table_DN_Temp.Select("SL not in ('CE','CN')").CopyToDataTable();
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("不存在符合CBM及重量计算的组件类型！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    //回刷MO_BOM数据到页面
                    DataTable dt_MO_NO = Common.DataTableHelper.Distinct(table_DN_Temp, new string[] { "MO_NO" });
                    DataTable dt_MO_BOM = Common.GetDataTable.Get_Table_NoOEM_BOM(dt_MO_NO);
                    //gridControl3.DataSource = dt_MO_BOM;
                    #endregion

                    #region OEM产品及配件CBM及重量计算

                    //***OEM产品CBM及重量计算
                    //***逻辑为SL not in ('CE','CN')，及非人工修正数据(Cal_Type != ‘人工修正’)，且PRODUCT_LINE='OEM'
                    if (table_DN_Temp.Select("PRODUCT_LINE='OEM' and Cal_Type<>'人工修正'").Length > 0)//???
                    {
                        //判断是否为OEM产品
                        //***如为OEM产品，计算并在’Cal_Type列写入’来源SAP'
                        DataTable table_DN_Temp_OEM = new DataTable();
                        table_DN_Temp_OEM = table_DN_Temp.Select("PRODUCT_LINE='OEM' and Cal_Type<>'人工修正' ").CopyToDataTable();
                        if (table_DN_Temp_OEM.Rows.Count > 0)
                        {
                            DataTable table_Material_OEM = Common.DataTableHelper.Distinct(table_DN_Temp_OEM, new string[] { "MATERIAL_NO" });
                            table_DN_Temp = Common.GetDataTable.Get_Table_OEM(table_DN_Temp, table_Material_OEM, table_UnitConvert);
                        }
                    }
                    //***配件CBM及重量计算
                    //***逻辑为SL not in ('CE','CN')，及非人工修正数据(Cal_Type != '人工修正")，且工艺路线包含D54、P79、或S20
                    //判断是否为配件产品
                    //???配件不属于OEM产品，同OEM产品同级
                    //***如为配件，计算并在’Cal_Type列写入’来源SAP'
                    //***速度太慢，此逻辑不需要取[开料尺寸]，只需要解析纸箱，请检查

                    if (table_DN_Temp.Select("Cal_Type<>'人工修正' and (PRODUCT_ROUTING like'%D54%' OR PRODUCT_ROUTING like'%P79%' OR PRODUCT_ROUTING like'%S20%') ").Length > 0)
                    {
                        DataTable table_DN_Temp_PJ = new DataTable();
                        table_DN_Temp_PJ = table_DN_Temp.Select("Cal_Type<>'人工修正' and (PRODUCT_ROUTING like'%D54%' OR PRODUCT_ROUTING like'%P79%' OR PRODUCT_ROUTING like'%S20%') ").CopyToDataTable();
                        if (table_DN_Temp_PJ.Rows.Count > 0)
                        {
                            // DataTable table_Material_PJ = Common.DataTableHelper.Distinct(table_DN_Temp_PJ, new string[] { "MATERIAL_NO" });
                            //table_DN_Temp = Common.GetDataTable.Get_Table_OEM(table_DN_Temp, table_Material_PJ, table_UnitConvert);

                            // update by Bill 2021.03.25
                            DataTable dt_Mo_Main = Common.DataTableHelper.Distinct(table_DN_Temp_PJ, new string[] { "MO_NO" });
                            DataTable table_DN_Temp_MO = Common.GetDataTable.Get_Table_NoOEM_BOM(dt_Mo_Main);//[MO_BOM]表
                            List<CartonMaterial> cartons = new List<CartonMaterial>();
                            DataTable dt_Carton_Mo = new DataTable();//定义纸箱包装的BOM数据表
                            cartons = Calculate.Fuc_CBM.CARTON_PACKING_CBM(table_DN_Temp_MO, dt_Mo_Main, out dt_Carton_Mo);
                            //纸箱包装
                            table_DN_Temp = Common.GetDataTable.Get_Table_PJ(table_DN_Temp, table_DN_Temp_PJ, table_UnitConvert, cartons);
                        }
                    }
                    #endregion

                    #region 钢脚重量和CBM计算
                    if (table_DN_Temp.Select("MRP_CONTROLLER='G00'").Length > 0)
                    {
                        DataTable dataTable = table_DN_Temp.Select("MRP_CONTROLLER='G00'").CopyToDataTable();
                        //Bill Test
                        //DataTable table_DN_List = Common.GetDataTable.GetTable_SA_DN_List(table_DN_Temp);
                        //var query = (from d in table_DN_Temp.AsEnumerable()
                        //             join l in table_DN_List.AsEnumerable()
                        //             on d.Field<string>("TRANSPORT_NO") equals l.Field<string>("TRANSPORT_NO")
                        //             where l.Field<string>("MRP_CONTROLLER") == "G00"
                        //             select d).ToList();


                        DataTable dt_Mo_Main1 = Common.DataTableHelper.Distinct(dataTable, new string[] { "MO_NO" });
                        DataTable table_DN_Temp_MO1 = Common.GetDataTable.Get_Table_NoOEM_BOM(dt_Mo_Main1);
                        List<CartonMaterial> cartons1 = new List<CartonMaterial>();
                        DataTable dt_Carton_Mo1 = new DataTable();//定义纸箱包装的BOM数据表
                        cartons1 = Calculate.Fuc_CBM.CARTON_PACKING_CBM(table_DN_Temp_MO1, dt_Mo_Main1, out dt_Carton_Mo1);
                        DataTable table_MateralParts = Common.GetDataTable.GetMertalParts(dataTable);
                        DataTable table_Decor = Common.GetDataTable.GetMertalParts_Decor();
                        table_DN_Temp = Common.GetDataTable.Get_Table_MetalParts(table_DN_Temp, dataTable, cartons1, table_MateralParts, table_Decor);

                    }
                    #endregion

                    #region 计算非OEM非配件产品CBM
                    //***逻辑为SL not in ('CE','CN')，及人工修正数据(Cal_Type列为入人工修正)，且PRODUCT_LINE='Laminate'
                    //非OEM桌子产品临时数据？？？
                    //***逻辑为SL not in ('CE','CN')，及非人工修正数据(Cal_Type != ‘人工修正’)，
                    //***且（PRODUCT_LINE !='OEM'，或工艺路线不包含D54、P79、或S20）


                    if (table_DN_Temp.Select("PRODUCT_LINE='Laminate' and Cal_Type <> '人工修正' ").Length > 0)
                    {
                        DataTable table_DN_Temp_NoOEM = table_DN_Temp.Select("PRODUCT_LINE='Laminate' and Cal_Type <> '人工修正' ").CopyToDataTable();
                        if (table_DN_Temp_NoOEM.Select(" PRODUCT_ROUTING like'%D44%' OR PRODUCT_ROUTING like'%D47%'").Length > 0)
                        {
                            DataTable dataTable = table_DN_Temp_NoOEM.Select(" PRODUCT_ROUTING like'%D44%' OR PRODUCT_ROUTING like'%D47%'").CopyToDataTable();
                            //增加工艺路线不包含D54、P79、或S20
                            if (dataTable.Select("PRODUCT_ROUTING not like'%D54%' AND PRODUCT_ROUTING not like'%P79%' AND PRODUCT_ROUTING not like'%S20%' ").Length > 0)
                            {
                                DataTable table_DN_Temp_NoOEM_Lamin = dataTable.Select("PRODUCT_ROUTING not like'%D54%' AND PRODUCT_ROUTING not like'%P79%' AND PRODUCT_ROUTING not like'%S20%' ").CopyToDataTable();
                                table_DN_Temp = Common.GetDataTable.Get_Table_NoOEM_Lamint(table_DN_Temp, table_DN_Temp_NoOEM_Lamin);
                            }
                        }
                    }

                    //非OEM非桌子组装
                    if (table_DN_Temp.Select("ISNULL(MO_NO,'')<>'' and PRODUCT_LINE<>'OEM' and Cal_Type <> '人工修正' ").Length > 0)
                    {
                        DataTable dt_Temp_MO = table_DN_Temp.Select("ISNULL(MO_NO,'')<>'' and PRODUCT_LINE<>'OEM' and Cal_Type <> '人工修正' ").CopyToDataTable();
                        //增加工艺路线不包含D54、P79、或S20
                        if (dt_Temp_MO.Select("PRODUCT_ROUTING not like'%D54%' AND PRODUCT_ROUTING not like'%P79%' AND PRODUCT_ROUTING not like'%S20%' ").Length > 0)
                        {
                            //增加工艺路线不包含D44、D47
                            DataTable dataTable = dt_Temp_MO.Select("PRODUCT_ROUTING not like'%D54%' AND PRODUCT_ROUTING not like'%P79%' AND PRODUCT_ROUTING not like'%S20%' ").CopyToDataTable();
                            if (dataTable.Select(" PRODUCT_ROUTING not like'%D44%' AND PRODUCT_ROUTING not like'%D47%'").Length > 0)
                            {
                                DataTable dt_MO = dataTable.Select(" PRODUCT_ROUTING not like'%D44%' AND PRODUCT_ROUTING not like'%D47%'").CopyToDataTable();
                                DataTable dt_Mo_Main = Common.DataTableHelper.Distinct(dt_MO, new string[] { "MO_NO" });
                                DataTable table_DN_Temp_MO = Common.GetDataTable.Get_Table_NoOEM_BOM(dt_Mo_Main);//[MO_BOM]表
                                List<CartonMaterial> cartons = new List<CartonMaterial>();
                                DataTable dt_Carton_Mo = new DataTable();//定义纸箱包装的BOM数据表
                                cartons = Calculate.Fuc_CBM.CARTON_PACKING_CBM(table_DN_Temp_MO, dt_Mo_Main, out dt_Carton_Mo);
                                //纸箱包装
                                if (cartons.Count > 0)
                                {
                                    table_DN_Temp = Common.GetDataTable.Get_Table_NoOEM_NoLamint(cartons, table_DN_Temp);
                                }
                                //其他包装
                                //获取两个数据表的差集（去掉纸箱包装的BOM，剩下的就是其他包装）
                                IEnumerable<DataRow> dt_CJ_TEMP = dt_Mo_Main.AsEnumerable().Except(dt_Carton_Mo.AsEnumerable(), DataRowComparer.Default);
                                if (dt_CJ_TEMP.ToList().Count > 0)
                                {
                                    DataTable dt_CJ_BOM = dt_CJ_TEMP.CopyToDataTable();
                                    if (dt_CJ_BOM.Rows.Count > 0)
                                    {
                                        DataTable dt_Board_Alum = new DataTable();//前台板材、铝材清单
                                        table_DN_Temp = Common.GetDataTable.Get_CutSizeTable(table_DN_Temp, table_DN_Temp_MO, dt_CJ_BOM, out dt_Board_Alum);
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region 计算非OEM及非配件产品重量
                    //***逻辑为SL not in ('CE','CN')，及非人工修正数据(Cal_Type != ‘人工修正’)，
                    //***且（PRODUCT_LINE !='OEM'，或工艺路线不包含D54、P79、或S20）
                    //***且MO_NO不为空
                    if (table_DN_Temp.Select("ISNULL(MO_NO,'')<>'' AND ISNULL(UNIT_WEIGHT,'0')='0' and Cal_Type <> '人工修正' and PRODUCT_LINE<>'OEM' ").Length > 0)
                    {
                        DataTable dt_Weight_Temp = table_DN_Temp.Select("ISNULL(MO_NO,'')<>'' AND ISNULL(UNIT_WEIGHT,'0')='0' and Cal_Type <> '人工修正' and PRODUCT_LINE<>'OEM' ").CopyToDataTable();
                        //增加工艺路线不包含D54、P79、或S20
                        if (dt_Weight_Temp.Select("PRODUCT_ROUTING not like'%D54%' AND PRODUCT_ROUTING not like'%P79%' AND PRODUCT_ROUTING not like'%S20%' ").Length > 0)
                        {
                            DataTable dt_Weight = dt_Weight_Temp.Select("PRODUCT_ROUTING not like'%D54%' OR PRODUCT_ROUTING not like'%P79%' OR PRODUCT_ROUTING not like'%S20%' ").CopyToDataTable();
                            //称重计重法
                            //***适用PRODUCT_LINE='Seating' OR PRODUCT_LINE='MCG'
                            if (dt_Weight.Select("PRODUCT_LINE='Seating' OR PRODUCT_LINE='MCG'").Length > 0)
                            {
                                DataTable dt_Weight_Seat_MCG = dt_Weight.Select("PRODUCT_LINE='Seating' OR PRODUCT_LINE='MCG'").CopyToDataTable();
                                DataTable dt_Mo_Main = Common.DataTableHelper.Distinct(dt_Weight_Seat_MCG, new string[] { "MO_NO" });
                                table_DN_Temp = Common.GetDataTable.Get_Table_NoOEM_Weight(table_DN_Temp, dt_Mo_Main, dt_MO_BOM);
                            }

                            //BOM计重法
                            //***适用PRODUCT_LINE='Laminate' OR PRODUCT_LINE='Panel'
                            if (dt_Weight.Select("PRODUCT_LINE='Laminate' OR PRODUCT_LINE='Panel'").Length > 0)
                            {
                                DataTable dt_Weight_Lamin_Panel = dt_Weight.Select("PRODUCT_LINE='Laminate' OR PRODUCT_LINE='Panel'").CopyToDataTable();
                                DataTable dt_Mo_Main = Common.DataTableHelper.Distinct(dt_Weight_Lamin_Panel, new string[] { "MO_NO" });
                                DataTable table_DN_Temp_MO = Common.GetDataTable.Get_Table_NoOEM_BOM(dt_Mo_Main);//[MO_BOM]表
                                DataTable dt_Weight_Per_Square = Common.GetDataTable.Get_Weight_Per_Square();
                                DataTable dt_Board_Alum = new DataTable();//前台板材、铝材清单
                                table_DN_Temp = Common.GetDataTable.Get_Table_NoOEM_BOM_Weight(table_DN_Temp, table_DN_Temp_MO, dt_Mo_Main, dt_Weight_Per_Square, table_cbm_wt, dt_MO_BOM, out dt_Board_Alum);

                            }
                        }
                    }
                    #endregion


                    #region 计算[临时DN表]出货CBM及重量
                    table_DN_Temp = Common.GetDataTable.Get_Table_CBM_Weight(table_DN_Temp);
                    #endregion

                    #region 回写数据表
                    //删除重复数据
                    Common.CRUDHelper.Delete_Table(table_DN_Temp);
                    if (Common.CRUDHelper.Insert_Batch(table_DN_Temp, "SA_CBM_WT_Calculated"))
                    {
                        //成功插入刷新页面
                        Refreshes();
                    }
                    #endregion
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无DN单数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.CloseSplashScreen();
            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        //导出Excel
        private void DoExport()
        {
            try
            {
                HKlink.Text = "";
                EXlink.Text = "";
                PRClink.Text = "";
                if (!Directory.Exists(@"D:\MESTemp"))
                    Directory.CreateDirectory(@"D:\MESTemp");
                //HK单本地存储位置
                string path_HK = @"D:\MESTemp\HK_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".xlsx";
                //EX单本地存储位置
                string path_EX = @"D:\MESTemp\EX_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".xlsx";
                //PRC单本地存储位置
                string path_PRC = @"D:\MESTemp\PRC_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".xlsx";

                //导出处理HK单Excel
                string listType_HK = "";
                if (strBUList.Contains("HK") || strBUList.Length <= 0)
                {
                    listType_HK = "HK";
                    DataTable table_HK = Common.CRUDHelper.GetExportFormat(listType_HK, strWhere_DT + strWhere_DN);
                    if (table_HK.Rows.Count > 0)
                    {
                        if (Common.ExcelHelpers.DataTableToExcel(table_HK, path_HK, true))
                        {
                            //显示到前台右上角
                            HKlink.Text = "点击打开HK单";
                            HKlink.Links.Clear();
                            HKlink.Links.Add(0, 7, path_HK);
                        }
                    }
                }
                //导出处理EX单Excel
                string listType_EX = "";
                if (strBUList.Contains("EX") || strBUList.Length <= 0)
                {
                    listType_EX = "EX";
                    DataTable table_EX = Common.CRUDHelper.GetExportFormat(listType_EX, strWhere_DT + strWhere_DN);
                    if (table_EX.Rows.Count > 0)
                    {
                        if (Common.ExcelHelpers.DataTableToExcel(table_EX, path_EX, true))
                        {
                            //显示到前台右上角
                            EXlink.Text = "点击打开EX单";
                            EXlink.Links.Clear();
                            EXlink.Links.Add(0, 7, path_EX);
                        }
                    }
                }
                if (dt_FinishCal.Select("TRANSPORT_NO LIKE 'TX%'OR TRANSPORT_NO LIKE 'SH%' OR TRANSPORT_NO LIKE 'BJ%' OR TRANSPORT_NO LIKE 'SCDMO%'").Length > 0)
                {
                    DataTable table_Temp = dt_FinishCal.Select("TRANSPORT_NO LIKE 'TX%'OR TRANSPORT_NO LIKE 'SH%' OR TRANSPORT_NO LIKE 'BJ%' OR TRANSPORT_NO LIKE 'SCDMO%'").CopyToDataTable();
                    DataTable table_PRC = Common.DataTableHelper.LinqToDataTableGroup(table_Temp);
                    //增加体积或重量为0时，Excel列的值需修改为0
                    for (int i = 0; i < table_PRC.Rows.Count; i++)
                    {
                        DataTable Temp = table_Temp.Select("TRANSPORT_NO='" + table_PRC.Rows[i]["出货单编号"].ToString() + "'").CopyToDataTable();
                        for (int j = 0; j < Temp.Rows.Count; j++)
                        {
                            double valuesCBM = Temp.Rows[j]["SHIPPING_VOLUME"].ToString().Length > 0 ?
                                     Convert.ToDouble(Temp.Rows[j]["SHIPPING_VOLUME"].ToString()) : 0;
                            double valuesWeight = Temp.Rows[j]["SHIPPING_WEIGHT"].ToString().Length > 0 ?
                              Convert.ToDouble(Temp.Rows[j]["SHIPPING_WEIGHT"].ToString()) : 0;
                            DataRow[] arrRows = table_PRC.Select("出货单编号='" + table_PRC.Rows[i]["出货单编号"].ToString() + "' " +
                                   " and 订单号码='" + table_PRC.Rows[i]["订单号码"].ToString() + "'" +
                                   " and 客户名称='" + table_PRC.Rows[i]["客户名称"].ToString() + "'");
                            if (valuesCBM == 0)
                            {
                                foreach (DataRow row in arrRows)
                                {
                                    row["体积"] = valuesCBM;
                                }
                            }
                            if (valuesWeight == 0)
                            {
                                foreach (DataRow row in arrRows)
                                {
                                    row["重量"] = valuesWeight;
                                }
                            }
                            if (valuesCBM == 0 && valuesWeight == 0)
                                break;
                        }
                    }
                    //导出处理PRC单Excel
                    if (Common.ExcelHelpers.DataTableToExcel(table_PRC, path_PRC, false))
                    {
                        //显示到前台右上角
                        PRClink.Text = "点击打开PRC单";
                        PRClink.Links.Clear();
                        PRClink.Links.Add(0, 8, path_PRC);
                    }
                }

            }
            catch (Exception ex)
            {
            }
        }

        #region Excel链接
        private void HKlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            HKlink.Links[HKlink.Links.IndexOf(e.Link)].Visited = true;
            string targetUrl = e.Link.LinkData as string;
            if (string.IsNullOrEmpty(targetUrl))
                DevExpress.XtraEditors.XtraMessageBox.Show("找不到链接地址,文件生成失败！");
            else
                System.Diagnostics.Process.Start(targetUrl);
        }
        private void EXlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            EXlink.Links[EXlink.Links.IndexOf(e.Link)].Visited = true;
            string targetUrl = e.Link.LinkData as string;
            if (string.IsNullOrEmpty(targetUrl))
                DevExpress.XtraEditors.XtraMessageBox.Show("找不到链接地址,文件生成失败！");
            else
                System.Diagnostics.Process.Start(targetUrl);
        }

        private void PRClink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            PRClink.Links[PRClink.Links.IndexOf(e.Link)].Visited = true;
            string targetUrl = e.Link.LinkData as string;
            if (string.IsNullOrEmpty(targetUrl))
                DevExpress.XtraEditors.XtraMessageBox.Show("找不到链接地址,文件生成失败！");
            else
                System.Diagnostics.Process.Start(targetUrl);
        }
        #endregion

        private void sbtnSendMail_Click(object sender, EventArgs e)
        {
            try
            {
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));

                if (dt_SendMail1.Rows.Count > 0)
                {
                    //string[] strAdress = { "Bill.Luo@lamex.com.hk" };//收件人
                    //string[] strCC = { "Bill.Luo@lamex.com.hk" };//{ "zhongjie.yang@lamex.com.hk", "eileen.wong@lamex.com.hk" };//抄送

                    string[] strAdress = { "TX-PUR-OEM@lamex.com.hk", "mingzhong.wu@lamex.com.hk" };
                    string[] strCC = { "chazi.wang@lamex.com.hk", "zhongjie.yang@lamex.com.hk", "eileen.wong@lamex.com.hk" };//抄送
                    Common.MailHelper.SendMailUseGmail("598", strAdress, strCC, dt_SendMail1);
                }
                if (dt_SendMail2.Rows.Count > 0)
                {
                    string[] strAdress = { "shuming.su@lamex.com.hk", "mingzhong.wu@lamex.com.hk" };
                    string[] strCC = { "eva.he@lamex.com.hk", "zhongjie.yang@lamex.com.hk", "eileen.wong@lamex.com.hk" };//抄送
                    Common.MailHelper.SendMailUseGmail("596&696", strAdress, strCC, dt_SendMail2);
                }
                if (dt_SendMail3.Rows.Count > 0)
                {
                    string[] strAdress = { "eileen.wong@lamex.com.hk" };//收件人
                    string[] strCC = { "zhongjie.yang@lamex.com.hk" };
                    Common.MailHelper.SendMailUseGmail("标准产品", strAdress, strCC, dt_SendMail3);
                }

                SplashScreenTool.CloseSplashScreen();
            }
            catch
            {
                SplashScreenTool.CloseSplashScreen();
            }
        }
    }
}
